<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ko" lang="ko">
<head>
<title>Javascript 二维码生成库：QRCode</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no" />
<script type="text/javascript" src="./js/jquery.min.js"></script>
<script type="text/javascript" src="./js/qrcode.min.js"></script>
</head>
<body>
<input id="text" type="text" value="http://www.runoob.com" style="width:80%" /><br />
<div id="qrcode" style="width:200px; height:200px; margin-top:15px; margin: 0px auto; border: 25px solid rgb(255, 255, 255);"></div>

<button id="downBtn">下载</button>

<script type="text/javascript">
var qrcode = new QRCode(document.getElementById("qrcode"), {
	// text: qrCodeContent,   // 二维码内容
	width: 128,  
	height: 128,
	colorDark : "#000000",  // 码的颜色
	colorLight : "#ffffff",  // 码的背景色
	correctLevel : QRCode.CorrectLevel.H,  // 高度容错
});

function makeCode () {		
	var elText = document.getElementById("text");
	if (!elText.value) {
		alert("Input a text");
		elText.focus();
		return;
	}
	// qrcode.clear(); // 可以清除二维码
	qrcode.makeCode(elText.value);
}

makeCode();

$("#text").
	on("blur", function () {
		makeCode();
	}).
	on("keydown", function (e) {
		if (e.keyCode == 13) {
			makeCode();
		}
	});

$("#downBtn").on("click", function(){
    const qrCodeDiv = document.getElementById('qrcode');  // 找到二维码div
    const url = qrCodeDiv.querySelector('canvas').toDataURL('image/png');          // 获取图片地址
  	const a = document.createElement('a');          // 创建一个a节点插入的document
    const handle = new MouseEvent('click')           // 模拟鼠标click点击事件
    a.download = "1112233";                // 设置a节点的download属性值
    a.href = url;                                 // 将图片的src赋值给a节点的href
    a.dispatchEvent(handle)            // 触发点击
})

</script>
</body>
</html>